package com.aldobucchi.x.mx.effects
{
	
	
	import flash.display.DisplayObject;
	import flash.utils.Dictionary;
	
	import mx.effects.Effect;
	import mx.events.EffectEvent;
	
	import com.aldobucchi.core.dependency.DependencySpec;
	import com.aldobucchi.core.dependency.MXMLObjectWithDependenciesBase;
	import com.aldobucchi.x.flash.events.EventListenerSpec;


	/**
	 * 
	 * Helper that hides display objects during an effect playback
	 * 
	 * @author aldo.bucchi@gmail.com
	 * 
	 */
	public class HideDisplayObjects extends MXMLObjectWithDependenciesBase
	{
		
		
		////////////////////////////////////////////////
		// effect
		////////////////////////////////////////////////
		
		private var effectSpec:DependencySpec = new DependencySpec( 
			"effect", 
			"effectChanged",
			[ 
				new EventListenerSpec( EffectEvent.EFFECT_START, effect_start, false, 0, true ) ,
				new EventListenerSpec( EffectEvent.EFFECT_END, effect_end, false, 0, true )
			]
			);
		[Bindable("effectChanged")]
		public function get effect( ):Effect
		{
			return dh.getDependencyValue( effectSpec ) as Effect;
		}
		public function set effect( v:Effect ):void
		{
			dh.setDependencyValue( effectSpec, v );
		}	
		


		////////////////////////////////////////////////
		// displayObjects
		////////////////////////////////////////////////

		private var displayObjectsSpec:DependencySpec = new DependencySpec( 
				"displayObjects" ,
				"displayObjectsChanged"		
			);
		public function get displayObjects( ):Array
		{
			return dh.getDependencyValue( displayObjectsSpec );
		}
		public function set displayObjects( v:Array ):void
		{
			dh.setDependencyValue( displayObjectsSpec, v );
		}
		
		
		
		
		
		private var previousVisibility:Dictionary = new Dictionary( true );
		
		
		
		
		public function HideDisplayObjects( effect:Effect=null, displayObjects:Array=null )
		{
			this.effect = effect;
			this.displayObjects = displayObjects;
		}
		
		
		
		
		
		private function effect_start( event:EffectEvent ):void
		{
			if ( displayObjects == null )
				return;
			
			// store previous visibility and hide items	
			for each ( var k:* in displayObjects )
			{
				if ( k is DisplayObject )
				{
					var dobj:DisplayObject = k as DisplayObject;
					previousVisibility[ dobj ] = dobj.visible;
					dobj.visible = false;			
				}					
			}


		}
		
		

		private function effect_end( event:EffectEvent ):void
		{
					
			if ( displayObjects == null )
				return;
			
			for ( var k:* in previousVisibility )
			{
				( k as DisplayObject ).visible = previousVisibility[ k ];
				delete previousVisibility[ k ];			
			}
		
		}
		
		
		
		
		
		
		
		
		
	}
}